package org.sun.web.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.inject.Inject;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.sun.basic.dao.IGroupDao;
import org.sun.basic.dao.IUserDao;
import org.sun.basic.model.Group;
import org.sun.basic.model.SysUser;
import org.sun.web.util.Constant;


public class CustomUserDetailsService implements UserDetailsService {
	
	@Inject
	private IUserDao userDao;
	
	@Inject
	private IGroupDao groupDao;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserDetails user=null;
		SysUser u=(SysUser)userDao.queryObject("from SysUser where name=?", username);
		
		if(u==null) throw new UsernameNotFoundException("用户名不存在！"); 
		
		user=setAuthStatus(u);
		
		return user;
	}
	
	public UserDetails setAuthStatus(SysUser user){
		UserDetails u=null;
		boolean enable=user.getStatus()==Constant.STATUS?true:false;
		boolean accountNonExpired=enable;
		boolean credentialsNonExpired=enable;
		boolean accountNonLocked=enable;
		u=new User(user.getName(), user.getPassword(), enable, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(user.getId()));
		return u;
	}
	
	public Collection<GrantedAuthority> getAuthorities(String id){
		List<GrantedAuthority> autlist= new ArrayList<GrantedAuthority>(2);
		String sql="select grp_id ,usr_id from usr_grp_rel where usr_id=?";
		List<Object[]> os= userDao.queryList(sql, id);
		for(Object[] o:os){
			Group g=groupDao.load(o[0].toString());
			autlist.add(new SimpleGrantedAuthority(g.getGrpcode()));
		}
		return autlist;
	}

}
